package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SpringSecurityUserService implements UserDetailsService {
    //模拟数据库中数据
    //创建map集合,键值对的数据
    private Map<String, User> map = new HashMap<>();
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //初始化方法
    public void initUserData(){
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));//使用bcrypt提供的方法对密码进行加密

        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("admin"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    //根据用户名查用户数据
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //初始化数据
        initUserData();

        //根据前端输入的用户名查询用户信息
        User user = map.get(username);
        if (user == null) {
            //如果不存在该用户,返回null
            return null;
        }else {
            ArrayList<GrantedAuthority> authorities = new ArrayList<>();
            //为当前登录用户授权
            authorities.add(new SimpleGrantedAuthority("permission_A"));
            authorities.add(new SimpleGrantedAuthority("permission_B"));

            if ("admin".equals(username)) {
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//授予角色
                authorities.add(new SimpleGrantedAuthority("add"));
            }
            org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);
            return securityUser;
        }
    }
}
